<template>
  <a-card size="small" :bordered="false" class="performance-monitor">
    <template #title>
      <div class="monitor-title">
        <dashboard-outlined />
        性能监控
      </div>
    </template>

    <div class="performance-metrics">
      <!-- 缓存统计 -->
      <div class="metric-group">
        <div class="metric-label">缓存状态</div>
        <div class="metric-item">
          <span class="metric-name">SVG缓存:</span>
          <a-progress :percent="svgCacheUsage" size="small" :strokeColor="getCacheColor(svgCacheUsage)" :format="(percent) => `${svgCacheStats.size}/${svgCacheStats.maxSize}`" />
        </div>
        <div class="metric-item">
          <span class="metric-name">元数据缓存:</span>
          <a-progress :percent="metaCacheUsage" size="small" :strokeColor="getCacheColor(metaCacheUsage)" :format="(percent) => `${metaCacheStats.size}/${metaCacheStats.maxSize}`" />
        </div>
      </div>

      <!-- 加载统计 -->
      <div class="metric-group">
        <div class="metric-label">加载统计</div>
        <div class="metric-grid">
          <div class="metric-card">
            <div class="metric-value">{{ loadStats.totalIcons }}</div>
            <div class="metric-desc">总图标数</div>
          </div>
          <div class="metric-card">
            <div class="metric-value">{{ loadStats.loadedIcons }}</div>
            <div class="metric-desc">已加载</div>
          </div>
          <div class="metric-card">
            <div class="metric-value">{{ loadStats.visibleIcons }}</div>
            <div class="metric-desc">可见</div>
          </div>
        </div>
      </div>

      <!-- 性能指标 -->
      <div class="metric-group">
        <div class="metric-label">性能指标</div>
        <div class="metric-grid">
          <div class="metric-card">
            <div class="metric-value">{{ formatTime(performanceStats.avgLoadTime) }}</div>
            <div class="metric-desc">平均加载</div>
          </div>
          <div class="metric-card">
            <div class="metric-value">{{ formatSize(performanceStats.memoryUsage) }}</div>
            <div class="metric-desc">内存占用</div>
          </div>
          <div class="metric-card">
            <div class="metric-value">{{ performanceStats.fps }}fps</div>
            <div class="metric-desc">渲染帧率</div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="metric-actions">
        <a-button size="small" @click="clearCache" :loading="clearing">
          <template #icon><delete-outlined /></template>
          清理缓存
        </a-button>
        <a-button size="small" @click="refreshStats">
          <template #icon><reload-outlined /></template>
          刷新统计
        </a-button>
      </div>
    </div>
  </a-card>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { DashboardOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

const props = defineProps({
  cacheInstances: {
    type: Object,
    required: true
  },
  loadStats: {
    type: Object,
    default: () => ({
      totalIcons: 0,
      loadedIcons: 0,
      visibleIcons: 0
    })
  }
})

const emit = defineEmits(['cache-cleared'])

// 响应式数据
const clearing = ref(false)
const svgCacheStats = ref({ size: 0, maxSize: 0, usage: 0 })
const metaCacheStats = ref({ size: 0, maxSize: 0, usage: 0 })
const performanceStats = ref({
  avgLoadTime: 0,
  memoryUsage: 0,
  fps: 0
})

// 计算属性
const svgCacheUsage = computed(() => svgCacheStats.value.usage)
const metaCacheUsage = computed(() => metaCacheStats.value.usage)

// 性能监控
let performanceMonitor = null
let fpsCounter = null

// 更新缓存统计
const updateCacheStats = () => {
  if (props.cacheInstances.svgCache) {
    svgCacheStats.value = props.cacheInstances.svgCache.getStats()
  }
  if (props.cacheInstances.metaCache) {
    metaCacheStats.value = props.cacheInstances.metaCache.getStats()
  }
}

// 获取缓存颜色
const getCacheColor = (usage) => {
  if (usage < 50) return '#52c41a'
  if (usage < 80) return '#faad14'
  return '#f5222d'
}

// 格式化时间
const formatTime = (ms) => {
  if (ms < 1000) return `${Math.round(ms)}ms`
  return `${(ms / 1000).toFixed(1)}s`
}

// 格式化大小
const formatSize = (bytes) => {
  if (bytes < 1024) return `${bytes}B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
}

// 监控内存使用
const monitorMemory = () => {
  if (window.performance && window.performance.memory) {
    performanceStats.value.memoryUsage = window.performance.memory.usedJSHeapSize
  }
}

// 监控FPS
const monitorFPS = () => {
  let lastTime = performance.now()
  let frames = 0

  const calculateFPS = (currentTime) => {
    frames++
    if (currentTime >= lastTime + 1000) {
      performanceStats.value.fps = Math.round((frames * 1000) / (currentTime - lastTime))
      frames = 0
      lastTime = currentTime
    }
    fpsCounter = requestAnimationFrame(calculateFPS)
  }

  fpsCounter = requestAnimationFrame(calculateFPS)
}

// 清理缓存
const clearCache = async () => {
  clearing.value = true
  try {
    if (props.cacheInstances.svgCache) {
      props.cacheInstances.svgCache.clear()
    }
    if (props.cacheInstances.metaCache) {
      props.cacheInstances.metaCache.clear()
    }

    updateCacheStats()
    emit('cache-cleared')
    message.success('缓存清理完成')
  } catch (error) {
    message.error('缓存清理失败')
  } finally {
    clearing.value = false
  }
}

// 刷新统计
const refreshStats = () => {
  updateCacheStats()
  monitorMemory()
  message.success('统计数据已刷新')
}

// 生命周期
onMounted(() => {
  updateCacheStats()

  // 定期更新统计
  performanceMonitor = setInterval(() => {
    updateCacheStats()
    monitorMemory()
  }, 2000)

  // 开始FPS监控
  monitorFPS()
})

onUnmounted(() => {
  if (performanceMonitor) {
    clearInterval(performanceMonitor)
  }
  if (fpsCounter) {
    cancelAnimationFrame(fpsCounter)
  }
})
</script>

<style scoped>
.performance-monitor {
  margin-bottom: 16px;
}

.monitor-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.performance-metrics {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.metric-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.metric-label {
  font-size: 12px;
  font-weight: 600;
  color: #666;
  margin-bottom: 4px;
}

.metric-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.metric-name {
  min-width: 80px;
  color: #666;
}

.metric-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

.metric-card {
  text-align: center;
  padding: 8px;
  background: #fafafa;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}

.metric-value {
  font-size: 14px;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 2px;
}

.metric-desc {
  font-size: 10px;
  color: #999;
}

.metric-actions {
  display: flex;
  gap: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.metric-actions .ant-btn {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .metric-grid {
    grid-template-columns: 1fr;
  }

  .metric-actions {
    flex-direction: column;
  }
}
</style>
